import React, { useEffect, useState, useRef } from 'react'
import { NavigationStackScreenComponent } from 'react-navigation-stack'
import { View, ScrollView, Text, TouchableOpacity, Image } from 'react-native'
import { ShortBar, InfoLayout, Toast } from 'components'
import { OrderItem } from './components'
import { tradListStyle as styles, recognitionListStyle } from './styles'
import { commonStyle, translateSize } from 'styles'
import { PosAppTrade, PosCustomer, PosAppFee, PosAppBank } from 'api/pos';
import { getAuthorization, operate } from 'services/authorization';
import { navigateReplace, navigate } from 'services/navigation';
import assets from 'modules/assets';
import { dropdownIcon } from './components/choose-room/style';
import { getMoneyFen } from '../../utils/index';
/**
 * 收款
 * @param props
 */
const TradListScreen: NavigationStackScreenComponent<{
	tyoe: string
	tradeInfo: PosAppTrade | PosAppFee
	bankList: PosAppBank
	scene: string
	onNext: () => void
}> = props => {
	const [tradeData, setTradetData] = useState<PosAppTrade>({ feeList: [] })
	const [feeList, setFeeList] = useState<PosAppFee>([])
	const checkData = useRef<String[]>([])
	const [showYs, setShowYs] = useState(false)
	const [showZt, setShowZt] = useState(false)

	useEffect(() => {
		let data = props.navigation.getParam('tradeInfo')
		setTradetData(data)
		setFeeList([...data.feeList] || [])
		props.navigation.setParams({
			onNext: () => {
				console.log('111', feeList)
				if (checkData.current.length == 0) {
					Toast.show('请选择款项')
					return
				}
				let checkFeeList: PosAppFee[] = []
				let setFlag = false
				try {
					data.feeList.forEach((item: PosAppFee) => {
						if (checkData.current.indexOf(item.erpId) > -1) {
							if (getMoneyFen(item.ye) > getMoneyFen(item.fundAmount) - getMoneyFen(item.fundActual)) {
								Toast.show(`${item.fundName}本次收款金额不能超过款项余额`)
								throw new Error(`${item.fundName}本次收款金额不能超过款项余额`)
							}
							if (item.fundAmount === item.fundActual) {
								Toast.show(`${item.fundName}已收齐`)
								throw new Error(`${item.fundName}已收齐`)
							}
							if (item.ifbg) {
								Toast.show(`${item.fundName}为在途款，不允许收款`)
								throw new Error(`${item.fundName}为在途款，不允许收款`)
							}
							if (!setFlag && item.ye <= 0) {
								setFlag = true
							}
							checkFeeList.push(item)
						}
					})
				} catch (e) {
					return
				}
				if (setFlag) {
					Toast.show(`请设置收款金额,收款金额必须大于0！`)
					return
				}

				console.log('222', checkFeeList)
				props.navigation.navigate('RecognitionConfirm', {
					tradeInfo: { ...data, feeList: checkFeeList },
					bankList: props.navigation.getParam('bankList'),
					scene: props.navigation.getParam('scene'),
					refId: data.erpId
					// customerInfo: props.navigation.getParam('customerInfo'),
				})
			},
		})
	}, [])

	return (
		<View style={commonStyle.containerColumn}>
			<View style={styles.titleContainer}>
				<View style={styles.projectContainer}>
					<ShortBar style={styles.title} title={getAuthorization().project.name} />
					<Text style={commonStyle.titleTag}>{props.navigation.getParam('tradeInfo').auartName} </Text>
					<TouchableOpacity
						style={commonStyle.headerRight}
						onPress={() => {
							operate()
							navigate('HandingFee', { tradeInfo: tradeData, bankList: props.navigation.getParam('bankList') })
						}}>
						<Text style={commonStyle.redTag}> 收取POS机手续费 </Text>
					</TouchableOpacity>
				</View>
				<Text style={{ ...styles.room, ...commonStyle.roomStyle }}> {props.navigation.getParam('tradeInfo').roomName || ''} </Text>
			</View>

			{/* <View style={styles.titleContainer}>
				<ShortBar style={styles.title} title={props.navigation.getParam('tradeInfo').roomName} />
				<Text style={styles.titleTag}>{props.navigation.getParam('tradeInfo').auartName} </Text>
				<Text
					style={{
						...commonStyle.tag,
						position: 'absolute',
						top: translateSize(43),
						right: translateSize(32),
					}}>
					收取POS机手续费
        </Text>
			</View> */}
			<ScrollView style={{ marginBottom: translateSize(203) }}>
				<View style={commonStyle.containerColumn}>
					{
						feeList.filter((fee: PosAppFee) => fee.ifbg).length > 0 ?
							<TouchableOpacity
								style={{ ...styles.projectContainer, paddingVertical: translateSize(10), paddingRight: translateSize(22), }}
								onPress={() => { operate(); setShowZt(!showZt) }}>
								<ShortBar style={styles.title} title='在途款项' />
								<Image source={showZt ? assets.images.icon_arrow_up : assets.images.icon_arrow_down} style={dropdownIcon} />
							</TouchableOpacity>
							: null
					}
					{showZt && feeList.filter((fee: any) => fee.ifbg).map((item: PosAppFee, index: number) => (
						<OrderItem
							data={item}
							key={`${index}`}
							onChange={(money, isCheck) => {

							}}
						/>
					))}
					{
						feeList.filter((fee: PosAppFee) => !fee.ifbg && fee.fundActual >= fee.fundAmount).length > 0 ?
							<TouchableOpacity
								style={{ ...styles.projectContainer, paddingVertical: translateSize(10), paddingRight: translateSize(22), }}
								onPress={() => { operate(); setShowYs(!showYs) }}>
								<ShortBar style={styles.title} title='已收款项' />

								<Image source={showYs ? assets.images.icon_arrow_up : assets.images.icon_arrow_down} style={dropdownIcon} />
							</TouchableOpacity>
							: null
					}
					{showYs && feeList.filter((fee: any) => !fee.ifbg && fee.fundActual >= fee.fundAmount).map((item: PosAppFee, index: number) => (
						<OrderItem
							data={item}
							key={`${index}`}
							onChange={(money, isCheck) => {

							}}
						/>
					))}
					{feeList.filter((fee: any) => !fee.ifbg && fee.fundActual < fee.fundAmount).map((item: PosAppFee, index: number) => (
						<OrderItem
							data={item}
							key={`${index}`}
							onChange={(money, isCheck) => {
								let data = checkData.current
								if (item.erpId && !isCheck) {
									data = checkData.current.filter(checkId => checkId != item.erpId)
								} else {
									data.push(item.erpId)
								}
								// item.ye = money
								let newFeeList = tradeData.feeList.map((fee) => {
									if (fee.erpId === item.erpId) {
										fee.ye = Number(money)
									}
									return fee
								})


								checkData.current = data
								setFeeList(newFeeList)
							}}
						/>
					))}
				</View>
			</ScrollView>
		</View>
	)
}

TradListScreen.navigationOptions = props => {
	return {
		title: '选择款项',
		headerRight: (
			<TouchableOpacity
				style={recognitionListStyle.headerRight}
				onPress={() => {
					operate()
					props.navigation.getParam('onNext')()
				}}>
				<Text style={recognitionListStyle.headerFont}>确认</Text>
			</TouchableOpacity>
		),
	}
}

export default TradListScreen
